package com.cheng.jkdemo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cheng.jkdemo.entity.AppKey;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/*
* 获取刷新密钥和请求密钥及过期时间
*/
public class GetAppKey {

    //appKey
    private String appKey = "c8f69d2de14d4460985170c06a34e2a7";
    //app密钥
    private String requestId = "d723503e064d429197fa96a68d9221af";

    public AppKey getAppKeyMain() {

        // 获取时间戳
        long requestTime = System.currentTimeMillis();

        //拼接参数
        StringBuffer sbf = new StringBuffer();
        sbf.append(appKey).append(requestId).append(requestTime);

        //生成MD5
        String sign = DigestUtils.md5DigestAsHex(sbf.toString().getBytes());

        //拼接请求参数  + "?" + appKey + "&" + requestId + "&" + sing + "&" + time
        String url = "http://dw.jinhua.gov.cn/gateway/app/refreshTokenByKey.htm" + "?" + "appKey=" + appKey + "&" + "sign=" + sign + "&" + "requestTime=" + requestTime;

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> resultsAppkey = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        String body = resultsAppkey.getBody();

        //转化成json对象
        JSONObject jsonObject = JSON.parseObject(body);
        System.out.println(jsonObject);

        JSONObject datas = jsonObject.getJSONObject("datas");
//      System.out.println(datas);

        //获取对象key
        String requestSecret = datas.getString("requestSecret");
        String requestSecretEndTime = datas.getString("requestSecretEndTime");

//        System.out.println("requestSecret:" + requestSecret);
//        System.out.println("requestSecretEndTime:" + requestSecretEndTime);
        return new AppKey(requestSecret,requestSecretEndTime);


/*        //获取数组
        JSONArray data = jsonObject.getJSONArray("datas");
        List<Object> list = JSONArray.parseArray(data.toJSONString(), Object.class);
        for (int i = 0; i < list.size(); i++) {
            JSONObject o = data.getJSONObject(i);
            System.out.println(o);
            String requestSecret = o.getString("requestSecret");
            String requestSecretEndTime = o.getString("requestSecretEndTime");
            return new AppKey(requestSecret,requestSecretEndTime);
            System.out.println("realName: " + realName + ", userName: " + userName);
        }
        return null; */
    }


    public static void main(String[] args) {
        new GetAppKey().getAppKeyMain();
    }
}
